import urllib.request
import urllib.error
import argparse
import xml.etree.ElementTree as etree 
import time
import csv

class ArinWhois:
    URL = 'http://whois.arin.net/rest'
    def getAS(self, asn):
        request = urllib.request.build_opener()
        try:
            res = request.open(self.URL + '/asn/{0}'.format(asn)).read()
        except(urllib.error.HTTPError):
            return {}
        restree = etree.fromstring(res)
        d = {}
        d['name'] = restree.find('{http://www.arin.net/whoisrws/core/v1}name').text
        return d
    
def main(output, AS_csv, registry):
    all_registry_asns = []
    with open(AS_csv,'r') as as_csv:
        as_reader = csv.reader(as_csv)
        for AS_range in as_reader:
            if not registry in AS_range[1]:
                continue
            if ('-' in AS_range[0]):
                first_as = int(AS_range[0].split('-')[0])
                second_as = int(AS_range[0].split('-')[1]) + 1
                all_registry_asns = all_registry_asns + list(range(first_as, second_as))
            else:
                all_registry_asns.append(int(AS_range[0]))
    with open(output,'w') as output:
        w = ArinWhois()
        for ASN in all_registry_asns:
            AS = w.getAS(ASN)
            if 'name' in AS:
                output.write('{0} {1}\n'.format(AS['name'], ASN))
            time.sleep(0.3)

if (__name__ == "__main__"):
    parser = argparse.ArgumentParser()
    parser.add_argument("output", )
    parser.add_argument("AS_csv",)
    parser.add_argument("registry",)
    args = parser.parse_args()
    main(**args.__dict__)